/**
 * 镜像更新状态管理 - 使用Pinia
 */

import { defineStore } from 'pinia'
import { STEP_TYPES, STEP_STATUS, ACTION_TYPES } from '../services/imageUpdateService.js'

export const useImageUpdateStore = defineStore('imageUpdate', {
  state: () => ({
    // 执行模式
    mode: 'manual', // 'auto' | 'manual'
    
    // 整体进度
    progress: 0,
    currentMessage: '',
    isRunning: false,
    
    // 步骤状态
    steps: {
      [STEP_TYPES.LWX_PARSE]: {
        type: STEP_TYPES.LWX_PARSE,
        name: 'LWX平台数据解析',
        status: STEP_STATUS.PENDING,
        message: '',
        data: null,
        error: null,
        startTime: null,
        endTime: null
      },
      [STEP_TYPES.IMAGE_VERIFY]: {
        type: STEP_TYPES.IMAGE_VERIFY,
        name: '智能镜像版本校验',
        status: STEP_STATUS.PENDING,
        message: '',
        data: null,
        error: null,
        startTime: null,
        endTime: null
      },
      [STEP_TYPES.CONDITIONAL_PULL]: {
        type: STEP_TYPES.CONDITIONAL_PULL,
        name: '条件性镜像拉取',
        status: STEP_STATUS.PENDING,
        message: '',
        data: null,
        error: null,
        startTime: null,
        endTime: null
      },
      [STEP_TYPES.CONTAINER_REBUILD]: {
        type: STEP_TYPES.CONTAINER_REBUILD,
        name: '智能容器重建',
        status: STEP_STATUS.PENDING,
        message: '',
        data: null,
        error: null,
        startTime: null,
        endTime: null
      }
    },
    
    // 执行上下文
    stepContext: {
      schoolName: '',
      schoolId: '',
      baseImage: '',
      fullImageUrl: '',
      composeFile: '',
      containerName: '',
      actionType: ACTION_TYPES.NONE,
      needsAction: false,
      patternInfo: null,
      nextSteps: null
    },
    
    // 日志记录
    logs: [],
    maxLogs: 1000,
    
    // WebSocket连接状态
    wsConnected: false,
    
    // 系统状态
    systemInfo: null,
    lastUpdateTime: null
  }),

  getters: {
    // 获取步骤列表
    stepList: (state) => {
      return Object.values(state.steps)
    },

    // 获取当前步骤
    currentStep: (state) => {
      const stepList = Object.values(state.steps)
      return stepList.find(step => step.status === STEP_STATUS.RUNNING) || 
             stepList.find(step => step.status === STEP_STATUS.PENDING)
    },

    // 获取已完成的步骤数
    completedStepsCount: (state) => {
      return Object.values(state.steps).filter(
        step => step.status === STEP_STATUS.SUCCESS
      ).length
    },

    // 获取总步骤数
    totalStepsCount: (state) => {
      return Object.keys(state.steps).length
    },

    // 计算进度百分比
    calculatedProgress: (state) => {
      const total = Object.keys(state.steps).length
      const completed = Object.values(state.steps).filter(
        step => step.status === STEP_STATUS.SUCCESS || step.status === STEP_STATUS.SKIPPED
      ).length
      const running = Object.values(state.steps).some(
        step => step.status === STEP_STATUS.RUNNING
      )
      
      let progress = (completed / total) * 100
      
      // 如果有步骤正在运行，给当前步骤添加一些进度
      if (running && completed < total) {
        progress += (1 / total) * 50 // 给运行中的步骤添加50%的权重
      }
      
      return Math.min(Math.round(progress), 100)
    },

    // 检查是否所有步骤都完成
    isAllStepsCompleted: (state) => {
      return Object.values(state.steps).every(
        step => step.status === STEP_STATUS.SUCCESS || step.status === STEP_STATUS.SKIPPED
      )
    },

    // 检查是否有错误
    hasErrors: (state) => {
      return Object.values(state.steps).some(step => step.status === STEP_STATUS.ERROR)
    },

    // 获取错误步骤列表
    errorSteps: (state) => {
      return Object.values(state.steps).filter(step => step.status === STEP_STATUS.ERROR)
    },

    // 获取最近的日志
    recentLogs: (state) => {
      return state.logs.slice(-50) // 最近50条日志
    },

    // 按级别过滤日志
    logsByLevel: (state) => {
      return (level) => state.logs.filter(log => log.level === level)
    },

    // 获取下一个可执行的步骤
    nextExecutableStep: (state) => {
      const stepOrder = [
        STEP_TYPES.LWX_PARSE,
        STEP_TYPES.IMAGE_VERIFY,
        STEP_TYPES.CONDITIONAL_PULL,
        STEP_TYPES.CONTAINER_REBUILD
      ]

      for (const stepType of stepOrder) {
        const step = state.steps[stepType]
        if (step.status === STEP_STATUS.PENDING || step.status === STEP_STATUS.ERROR) {
          // 检查前置步骤是否完成
          const currentIndex = stepOrder.indexOf(stepType)
          const previousStepsCompleted = stepOrder.slice(0, currentIndex).every(prevStepType => {
            const prevStep = state.steps[prevStepType]
            return prevStep.status === STEP_STATUS.SUCCESS || prevStep.status === STEP_STATUS.SKIPPED
          })
          
          if (previousStepsCompleted) {
            return step
          }
        }
      }
      
      return null
    },

    // 获取步骤显示颜色
    getStepColor: () => {
      return (status) => {
        switch (status) {
          case STEP_STATUS.PENDING:
            return '#d4d4d8'
          case STEP_STATUS.RUNNING:
            return '#3b82f6'
          case STEP_STATUS.SUCCESS:
            return '#10b981'
          case STEP_STATUS.ERROR:
            return '#ef4444'
          case STEP_STATUS.SKIPPED:
            return '#f59e0b'
          default:
            return '#6b7280'
        }
      }
    },

    // 整体进度 (使用计算出的进度或手动设置的进度)
    overallProgress: (state) => {
      return state.progress || state.calculatedProgress
    },

    // 系统是否已初始化
    isInitialized: (state) => {
      return state.systemInfo !== null
    }
  },

  actions: {
    // 设置执行模式
    setMode(mode) {
      this.mode = mode
      this.addLog('info', `切换到${mode === 'auto' ? '自动' : '手动'}模式`)
    },

    // 设置整体进度
    setProgress(progress) {
      this.progress = Math.min(Math.max(progress, 0), 100)
    },

    // 设置当前消息
    setCurrentMessage(message) {
      this.currentMessage = message
    },

    // 设置运行状态
    setRunning(isRunning) {
      this.isRunning = isRunning
      if (isRunning) {
        this.addLog('info', '开始执行镜像更新流程')
      }
    },

    // 设置步骤状态
    setStepStatus(stepType, status, message = '') {
      if (this.steps[stepType]) {
        const step = this.steps[stepType]
        
        // 记录时间戳
        if (status === STEP_STATUS.RUNNING && step.status !== STEP_STATUS.RUNNING) {
          step.startTime = new Date().toISOString()
        } else if (status !== STEP_STATUS.RUNNING && step.status === STEP_STATUS.RUNNING) {
          step.endTime = new Date().toISOString()
        }
        
        step.status = status
        step.message = message
        
        // 清除错误信息（如果状态不是错误）
        if (status !== STEP_STATUS.ERROR) {
          step.error = null
        }
        
        this.addLog('info', `步骤 ${step.name}: ${message || status}`)
      }
    },

    // 设置步骤数据
    setStepData(stepType, data) {
      if (this.steps[stepType]) {
        this.steps[stepType].data = data
      }
    },

    // 设置步骤错误
    setStepError(stepType, error) {
      if (this.steps[stepType]) {
        this.steps[stepType].error = error
        this.addLog('error', `步骤 ${this.steps[stepType].name} 失败: ${error}`)
      }
    },

    // 获取步骤数据
    getStepData(stepType) {
      return this.steps[stepType]?.data || {}
    },

    // 更新步骤上下文
    updateStepContext(updates) {
      this.stepContext = { ...this.stepContext, ...updates }
    },

    // 获取步骤上下文
    getStepContext() {
      return this.stepContext
    },

    // 重置所有步骤
    resetAllSteps() {
      Object.keys(this.steps).forEach(stepType => {
        this.steps[stepType].status = STEP_STATUS.PENDING
        this.steps[stepType].message = ''
        this.steps[stepType].data = null
        this.steps[stepType].error = null
        this.steps[stepType].startTime = null
        this.steps[stepType].endTime = null
      })
      
      this.progress = 0
      this.currentMessage = ''
      this.isRunning = false
      
      // 清空上下文（保留学校基本信息）
      const schoolName = this.stepContext.schoolName
      const schoolId = this.stepContext.schoolId
      
      this.stepContext = {
        schoolName,
        schoolId,
        baseImage: '',
        fullImageUrl: '',
        composeFile: '',
        containerName: '',
        actionType: ACTION_TYPES.NONE,
        needsAction: false,
        patternInfo: null,
        nextSteps: null
      }
      
      this.addLog('info', '重置所有步骤状态')
    },

    // 添加日志
    addLog(level, message, data = null) {
      const logEntry = {
        id: Date.now() + Math.random(),
        level,
        message,
        data,
        timestamp: new Date().toISOString(),
        displayTime: new Date().toLocaleTimeString()
      }
      
      this.logs.push(logEntry)
      
      // 限制日志数量
      if (this.logs.length > this.maxLogs) {
        this.logs.splice(0, this.logs.length - this.maxLogs)
      }
      
      console.log(`[${level.toUpperCase()}]`, message, data)
    },

    // 清空日志
    clearLogs() {
      this.logs = []
      this.addLog('info', '日志已清空')
    },

    // 设置WebSocket连接状态
    setWebSocketConnected(connected) {
      this.wsConnected = connected
      this.addLog('info', `WebSocket ${connected ? '已连接' : '已断开'}`)
    },

    // 更新系统信息
    updateSystemInfo(systemInfo) {
      this.systemInfo = systemInfo
      this.lastUpdateTime = new Date().toISOString()
    },

    // 从WebSocket消息更新状态
    handleWebSocketMessage(eventType, data) {
      switch (eventType) {
        case 'image_update_progress':
          if (data.progress !== undefined) {
            this.setProgress(data.progress)
          }
          if (data.message) {
            this.setCurrentMessage(data.message)
            this.addLog('info', data.message)
          }
          break
          
        case 'image_update_complete':
          this.setRunning(false)
          this.setProgress(100)
          this.addLog('success', '镜像更新完成')
          break
          
        case 'image_update_error':
          this.setRunning(false)
          this.addLog('error', `镜像更新失败: ${data.message || '未知错误'}`)
          break
          
        case 'execution_log':
          this.addLog(data.level || 'info', data.message, data.data)
          break
          
        case 'system_status':
          this.updateSystemInfo(data)
          break
      }
    },

    // 导出状态快照
    exportSnapshot() {
      return {
        mode: this.mode,
        progress: this.progress,
        currentMessage: this.currentMessage,
        isRunning: this.isRunning,
        steps: JSON.parse(JSON.stringify(this.steps)),
        stepContext: JSON.parse(JSON.stringify(this.stepContext)),
        logs: this.recentLogs,
        wsConnected: this.wsConnected,
        systemInfo: this.systemInfo,
        timestamp: new Date().toISOString()
      }
    }
  }
})